#include <iostream>
#include <cstdio>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include<cstring>


std::string Formatid(const pthread_t& tid)
{
    char buffer[64];
    //将tid格式化为16进制
    snprintf(buffer,sizeof(buffer),"0x%lx",tid);
    return buffer;
}

void*routine(void*args)
{
    std::string name=static_cast<const char*>(args);
    pthread_t tid=pthread_self();
    //线程分离
    pthread_detach(tid);
    int cnt=5;
    while(cnt--)
    {
        sleep(1);
        std::cout<<"我是新线程名字:"<<name<<"我的tid:"<<Formatid(tid)<<std::endl;
    }
    return (void*)0x123;
}

int main()
{
    pthread_t tid=0;
    int n=pthread_create(&tid,nullptr,routine,(void*)"thread_1");
    int cnt=5;
    while(cnt--)
    {
        std::cout<<"我是主进程tid:"<<Formatid(pthread_self())<<std::endl;
        sleep(1);
    }
    
    void*ret=nullptr;
    //新线程已分离等待错误
    n=pthread_join(tid,&ret);
    if(n!=0)
    {
        std::cerr<<"pthread_join failed"<<strerror(n)<<std::endl;
    }
    else
    {
        printf("pthread_join success!");
    }

    std::cout<<ret<<std::endl;

    return 0;
}